<template>
  <div class="exam-page flex-col">
    <div class="exam-selected-section flex-col">
      <div class="exam-option-group flex-row justify-between">
        <div
          class="exam-option"
          v-for="option in options"
          :key="option.value"
          @click="selectOption(option.value)"
          :class="{ selected: selectedOption === option.value }"
        >
          {{ option.label }}
        </div>
      </div>
      <div class="center-box">
        <span class="exam-list-title">推荐竞赛</span>
        <!-- <el-form
          inline="true"
          class="exam-navigation flex-row justifybetween"
        >
          <el-form-item
            label="竞赛时间"
            prop="datetimerange"
            class="examnavigation-box"
          >
            <el-date-picker
              style="width:360px;"
              v-model="searchTimer"
              type="datetimerange"
              range-separator="⾄"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button
              @click="onSearch"
              plain
              type="primary"
            >搜索</el-button>
            <el-button
              @click="onReset"
              plain
              type="info"
            >重置</el-button>
          </el-form-item>
        </el-form> -->
        <!-- </div> -->
        <div class="exam-list-group flex-row">
          <div
            class="exam-list-item flex-col"
            v-for="(exam, index) in
              examList"
            :key="index"
          >
            <div>
              <img src="@/assets/images/exam.png">
            </div>
            <div class="right-info">
              <span class="exam-title">{{ exam.title }}</span>
              <div class="exam-content flex-col justify-between">
                <span>开赛时间：{{ exam.startTime }}</span>
                <span>结束时间：{{ exam.endTime }}</span>
              </div>
              <!-- 竞赛按钮 -->
              <div class="exam-button-container">
                <span
                  class="exam-hash-entry"
                  v-if="isOngoingAndUnregisteredCompetition(exam)"
                >已开赛</span>
                <span
                  class="exam-hash-entry"
                  v-if="isEntryAndNotStart(exam)"
                >已报名</span>
                <div v-if="isHistoryExam(exam)">
                  <el-button
                    class="exam-practice-button"
                    type="primary"
                    plain
                    @click="goExam(exam)"
                  >竞赛练习</el-button>
                  <el-button
                    class="exam-rank-button"
                    type="primary"
                    plain
                    @click="togglePopover(exam.examId)"
                  >查看排名</el-button>
                </div>
                <el-button
                  class="exam-start-button"
                  type="primary"
                  plain
                  v-if="isStartExam(exam)"
                  @click="goExam(exam)"
                >开始答题</el-button>
                <el-button
                  class="exam-enter-button"
                  type="primary"
                  plain
                  v-if="isCanEntry(exam)"
                  @click="enterExam(exam)"
                >报名参赛</el-button>
              </div>
            </div>
          </div>
        </div>
        <div class="exam-page-pagination flex-row">
          <el-pagination
            background
            layout="total, sizes, prev, pager, next,
jumper"
            :total="total"
            v-model:current-page="params.pageNum"
            v-model:pageSize="params.pageSize"
            :page-sizes="[3, 6, 9, 12]"
            @size-change="handleSizeChange"
            @currentChange="handleCurrentChange"
          />
        </div>
      </div>
    </div>
  </div>

  <el-dialog v-model="dialogRankVisible" width="600px" top="30vh" :show-close="true" :close-on-click-modal="false"
    :close-on-press-escape="false" class="oj-login-dialog-centor" center>
    <el-table :data="rankList">
      <el-table-column label="排名" prop="userRank" />
      <el-table-column label="用户昵称" prop="nickName" />
      <el-table-column label="用户得分" prop="score" />
    </el-table>
    <el-pagination class="range_page" background layout="total, sizes, prev, pager, next, jumper" :total="rankTotal"
      v-model:current-page="rankQueryParams.pageNum" v-model:page-size="rankQueryParams.pageSize" :page-sizes="[5, 10, 15, 20]"
      @size-change="handleRankSizeChange" @current-change="handleRankCurrentChange" />
  </el-dialog>
</template>
<script setup>
  import { reactive, ref } from 'vue'
  import { getExamListService } from '@/apis/examApi'
  import { enterExamService, getRankListService } from '@/apis/userExamApi'
  import { ElMessage } from 'element-plus';

  import { getToken } from '@/utils/cookie'
  import router from '@/router';
  //参数定义
  const examList = ref([]) //题⽬列表
  const total = ref(0)
  const defaultType = 1;
  const selectedOption = ref(defaultType); // 初始化选中的⽂本
  const options = ref([
    { label: '未完赛', value: 1 },
    { label: '历史竞赛', value: 0 },
  ])
  const params = reactive({
    pageNum: 1,
    pageSize: 9,
    type: defaultType,
    startTime: '',
    endTime: '',
  })
  const searchTimer = ref([])
  //竞赛列表
  async function getExamList() {
    if (searchTimer.value.length > 0) {
      params.startTime = searchTimer.value[0]
      params.endTime = searchTimer.value[1]
    } else {
      params.startTime = ''
      params.endTime = ''
    }
    const result = await getExamListService(params)
    examList.value = result.rows
    total.value = result.total
  }
  getExamList()
  async function selectOption(type) {
    selectedOption.value = type
    params.pageNum = 1
    params.type = type
    getExamList()
  }
  // 搜索/重置
  function onSearch() {
    params.pageNum = 1
    getExamList()
  }
  function onReset() {
    params.pageNum = 1
    params.pageSize = 9
    params.type = 0
    getExamList()
  }
  // 分⻚
  function handleSizeChange(newSize) {
    params.pageNum = 1
    getExamList()
  }
  function handleCurrentChange(newPage) {
    getExamList()
  }

  function goExam(exam) {
    router.push({
      path: '/oj-c/anwser',
      query: {
        examId: exam.examId,
        title: exam.title,
        examEndTime: exam.endTime
      },
    })
  }

  // 竞赛按钮显示判断
  function isOngoingAndUnregisteredCompetition(exam) {
    const now = new Date(); //当前时间
    return new Date(exam.startTime) < now && new Date(exam.endTime) > now && !exam.enter
  }

  function isEntryAndNotStart(exam) {
    const now = new Date();
    return new Date(exam.startTime) > now && exam.enter
  }

  function isHistoryExam(exam) {
    const now = new Date();
    return new Date(exam.endTime) < now;
  }

  function isStartExam(exam) {
    const now = new Date();
    return new Date(exam.startTime) < now && new Date(exam.endTime) > now && exam.enter;
  }

  function isCanEntry(exam) {
    const now = new Date();
    return new Date(exam.startTime) > now && !exam.enter;
  }

  const isLogin = ref(false)
  async function checkLogin() {
    if (getToken()) {
      isLogin.value = true
    }
  }
  async function enterExam(exam) {
    // 先检查是否登录
    await checkLogin()
    if (!isLogin.value) {
      ElMessage.error('当前还未登录，请先登录')
      return
    }
    await enterExamService({
      examId: exam.examId
    })
    ElMessage.success('您已报名成功，请按时参赛',)
    getExamList() //报名成功后刷新竞赛列表
  }

  // 查看排名
  const dialogRankVisible = ref(false)
  const rankList = ref([])
  const rankTotal = ref(0)

  const rankQueryParams = reactive({
    examId: '',
    pageNum: 1,
    pageSize: 10
  })

  async function getRankList(examId) { 
    rankQueryParams.examId = examId || rankQueryParams.examId
    const { total, rows } = await getRankListService(rankQueryParams)
    rankList.value = rows
    rankTotal.value = total
  }

  async function handleRankSizeChange(value) {
    rankQueryParams.pageNum = 1
    rankQueryParams.pageSize = value
    getRankList()
  }

  async function handleRankCurrentChange(value) {
    rankQueryParams.pageNum = value
    getRankList()
  }

  async function togglePopover(examId) {
    dialogRankVisible.value = true
    if (dialogRankVisible.value) {
      getRankList(examId)
    }
  }
</script>

<style lang="scss" scoped>
  .exam-page {
    background-color: rgba(247, 247, 247, 1);
    position: relative;
    overflow: hidden;
    display: flex;

    .center-box {
      max-width: 1520px;
      margin: 0 auto;
      width: 100%;
      min-height: 368px;
      background: #FFFFFF;
      border-radius: 16px;
      padding: 0 20px;
      padding-top: 30px;
      margin-top: 10px;
    }

    .exam-selected-section {
      margin: 0 auto;
      margin-bottom: 20px;
      position: relative;
      padding-top: 50px;
      max-width: 1520px;
      width: 100%;

      .exam-option-group {
        width: fit-content;
        height: 50px;
        position: absolute;
        top: 0;
        left: 0;

        .exam-option {
          cursor: pointer;
          padding: 10px;
          border-bottom: 2px solid transparent;
          transition: all 0.3s ease;
          font-family: PingFangSC, PingFang SC;
          font-weight: 600;
          font-size: 18px;
          color: #222;
          height: 50px;
          width: fit-content;
          display: flex;
          justify-content: center;
          align-items: center;
          margin-right: 20px;
        }

        .exam-option.selected {
          color: #32C5FF;
          border-bottom: 2px solid #32C5FF;
        }
      }

      .exam-list-title {
        height: 24px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 600;
        font-size: 18px;
        color: #222222;
        line-height: 25px;
        text-align: left;
        margin-bottom: 30px;
        display: block;
      }

      :deep(.exam-navigation) {
        width: 554px;
        height: 40px;
        font-size: 100px;
        margin-bottom: 30px;

        .el-form-item {
          margin-right: 20px;
        }

        .el-form-item__label {
          background: #fff;
        }

        .exam-navigation-box {
          background-color: rgba(242, 243, 244, 1);
          border-radius: 6px;
          height: 30px;
          // width: 460px;
          font-weight: 700;
        }
      }

      .exam-list-group {
        // width: 1200px;
        flex-wrap: wrap;

        @media screen and (min-width: 1420px) {
          .exam-list-item {
            width: 32%;

            &:nth-of-type(3n) {
              margin-right: 0;
            }
          }
        }

        @media screen and (max-width: 1419px) {
          .exam-list-item {
            width: 48%;
            margin-right: 2%;

            &:nth-of-type(2n) {
              margin-right: 0;
            }
          }
        }

        @media screen and (max-width: 970px) {
          .exam-list-item {
            width: 100%;
            margin-right: 0;
          }
        }

        .exam-list-item {
          height: 220px;
          background: #F9F9F9;
          border-radius: 10px;
          margin-right: 2%;
          margin-bottom: 20px;
          padding: 20px;
          box-sizing: border-box;
          display: flex;
          align-items: center;
          flex-direction: row;
          justify-content: space-between;
          cursor: pointer;

          .right-info {
            width: calc(100% - 146px);
          }

          .exam-title {
            height: 26px;
            font-family: PingFangSC, PingFang SC;
            font-weight: 600;
            font-size: 18px;
            color: #222222;
            line-height: 26px;
            text-align: left;
            max-width: 90%;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            margin-bottom: 16px;
            display: block;
          }

          .exam-content {
            margin-bottom: 26px;

            span {
              height: 22px;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 16px;
              color: #666666;
              line-height: 22px;
              display: block;
              margin-bottom: 12px;
            }
          }

          img {
            width: 126px;
            height: 180px;
            border-radius: 6px;
          }

          &:hover {
            background: #fff;
            box-shadow: 0px 0px 6px 0px rgba(0, 0, 0, 0.1);

            .exam-title {
              color: #32C5FF;
            }

            .el-button {
              background: #f7f7f7;
            }
          }

          .exam-hash-entry {
            float: right;
            font-size: 18px;
            font-family: PingFangSC-Regular, PingFang SC;
            font-weight: 400;
            color: #999;
          }

          .exam-button-container {
            display: flex;
            justify-content: space-between;
            /* 或者使⽤ flex-start 来紧密排列按钮 */
            align-items: center;

            /* 如果需要垂直居中 */
            /* 其他样式，如外边距、内边距等 */
            .el-button {
              width: 120px;
              height: 44px;
              background: #F7F7F7;
              border-radius: 4px;
              border: 1px solid #32C5FF;
              font-family: PingFangSC, PingFang SC;
              font-weight: 400;
              font-size: 18px;
              color: #32C5FF;
              line-height: 44px;
              text-align: center;
            }
          }
        }
      }

      .exam-page-pagination {
        width: 594px;
        height: 40px;
        margin: 30px 0 73px 800px;
      }
    }
  }
</style>